package org.ccay.core.util;

import java.io.File;

import org.ccay.core.util.exception.NetSecurityException;

/**
 * Net安全工具
 * 
 * 
 * @since 2012-3-26
 */
public final class NetSecurityUtil {
	/**
	 * 避免实例
	 */
	private NetSecurityUtil() {
	}

	/**
	 * 检查文件名是否包含路径
	 */
	public static void checkFileName(String fileName) {
		if (StringUtil.isNullOrEmpty(fileName)) {
			return;
		}

		if (fileName.contains("/") || fileName.contains("\\")) {
			throw new NetSecurityException("Dangerous file name.");
		}
	}

	/**
	 * 对字符串进行sql转换 推荐使用MessageFormat来进行sql语句的拼凑
	 * 
	 * @param string
	 * @return
	 */
	public static String getValidSQLPara(String string) {
		if (StringUtil.isNullOrEmpty(string)) {
			return string;
		}
		return string.replaceAll("'", "''");
	}

	/**
	 * 跨目錄文件操作检查，只有路径
	 * 
	 * 
	 * @since 2013-9-30
	 * @param path
	 * @return
	 */
	public static void checkPath(String path) {
		if (path != null && path.length() > 0) {
			if (path.indexOf("..") != -1) {
				throw new NetSecurityException("Dangerous path.");
			}
		}
	}
	
	/**
	 * 跨目錄文件操作检查,带文件名的路径
	 * 
	 * 
	 * @since 2013-9-30
	 * @param fileName
	 * @return
	 */
	public static void checkAbsulteFileName(String absulteFileName) {
		int pos = absulteFileName.lastIndexOf(File.separator);
		String path = absulteFileName.substring(0,pos);
		checkPath(path);
		String fileName = absulteFileName.substring(pos+1);
		checkFileName(fileName);
	}

}
